package com.ytktt.study.week4.task2;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.charset.StandardCharsets;

/**
 * 通过PipedStream做线程间通信
 *
 * @author ytk
 */
public class PipedStreamDemo {

    public static void main(String[] args) throws InterruptedException {
        try (PipedOutputStream out = new PipedOutputStream()) {
            PipedInputStream in = new PipedInputStream(out);
            new Thread(() -> {
                try {
                    int sum = sum();
                    out.write(String.valueOf(sum).getBytes(StandardCharsets.UTF_8));
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
            int receive;
            byte[] temp = new byte[1024];
            while ((receive = in.read(temp)) != -1) {
                String outStr = new String(temp, 0, receive);
                System.out.println("异步计算结果为：" + outStr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static int sum() {
        return fibo(36);
    }

    private static int fibo(int a) {
        if (a < 2) {
            return 1;
        }
        return fibo(a - 1) + fibo(a - 2);
    }
}
